/* Copyright (c) 2009 SpringShowcase, Inc.
 * All right reserved.
 * http://code.google.com/p/springshowcase/
 * This software is the confidential and proprietary information of BeyondWeb
 * , Inc. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement
 * you entered into with BeyondWeb.
 *
 * Revision History
 * Author              Date             Description
 * ------------------   --------------    ------------------
 *  taeki.kim           2010. 4. 6.        
 */
package org.springshowcase.core.mvc;

import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.view.AbstractView;

// TODO: Auto-generated Javadoc
/**
 * The Class JsonView.
 */
public class JsonView extends AbstractView {
	// ---------------------------------------------------------------------
	// Class Variable Declaration
	// ---------------------------------------------------------------------
	/** The Constant logger. */
	private static final Logger logger = LoggerFactory
			.getLogger(JsonView.class);
	public static final String CONTENT_OBJECT = "RESULT_OBJECT";
	
	/** The Constant CONTENT_TYPE. */
	private static final String CONTENT_TYPE = "application/json";

	/** The response body name. */
	private String responseBodyName;

	@Autowired
	private MessageSource messageSource;

	// ---------------------------------------------------------------------
	// Constructor Method Declaration
	// ---------------------------------------------------------------------
	/**
	 * Instantiates a new json view.
	 */
	public JsonView() {
		super();
		setContentType(CONTENT_TYPE);
	}

	// ---------------------------------------------------------------------
	// DI Method (setter,getter) Declaration
	// ---------------------------------------------------------------------

	/**
	 * @param responseBodyName the responseBodyName to set
	 */
	public void setResponseBodyName(String responseBodyName) {
		this.responseBodyName = responseBodyName;
	}

	// ---------------------------------------------------------------------
	// this Method (public/private) Declaration
	// ---------------------------------------------------------------------
	// ---------------------------------------------------------------------
	// interface implement Method (public/private) Declaration
	// ---------------------------------------------------------------------
	// ---------------------------------------------------------------------
	// abstract implement Method (public/private) Declaration
	// ---------------------------------------------------------------------
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel
	 * (java.util.Map, javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	protected void renderMergedOutputModel(Map model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("rendering ajax view..");
		PrintWriter writer;
		writer = response.getWriter();
		response.setContentType(getContentType());
		
		BindingResult bindingResult = (BindingResult) model
				.get("beanPropertyBindingResult");
		
		ExceptionLogBean exceptionLogBean = (ExceptionLogBean)model
		.get("exceptionLogBean");
		
		// 데이터 바인딩이 Invalid일 경우
		if (bindingResult != null && bindingResult.hasErrors()) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			
			List<BindingErrorMessageBean> errorMessages = BindingResultSupport
					.getBindErrorMessages(bindingResult, messageSource);
			
			JSONArray jsonObject = JSONArray.fromObject(errorMessages);
			writer.print(jsonObject);
		}else if(exceptionLogBean!=null) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			JSONArray jsonObject = JSONArray.fromObject(exceptionLogBean);
			writer.print(jsonObject);
		}
		else {
			Object responseObject = (Object) model.get(CONTENT_OBJECT);
			if (responseObject == null) {
				writer.print("{}");
			}
			else {
				if (responseObject instanceof Collection
						|| responseObject instanceof Object[]) {
					JSONArray jsonObject = JSONArray.fromObject(responseObject);
					writer.print(jsonObject);
				}
				else {
					JSONObject jsonObject = JSONObject
							.fromObject(responseObject);
					writer.print(jsonObject);
				}
			}
		}
	}
	// ---------------------------------------------------------------------
	// abstract Method (public/private) Declaration
	// ---------------------------------------------------------------------

}
